package cn.aliang.cloud.hystrixpayment.service;

import cn.aliang.cloud.service.entity.ResultCode;
import cn.aliang.cloud.service.entity.ResultMessage;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

/**
 * @Author: chendongliang
 * @Date: 2020/7/21 15:35
 */

@Service
public class PaymentHystrixSerivce {

    @HystrixCommand(fallbackMethod = "payTimeoutFallback" //回调方法
          ,commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")
    })
    public ResultMessage payTimeout(String id) {
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new ResultMessage(ResultCode.OK.getCode(),"---超时接口正常调用，线程--"+Thread.currentThread().getName());
    }
    /***
     *  超时降级回调方法
     */
    public ResultMessage payTimeoutFallback(String id){
       return new ResultMessage(ResultCode.OK.getCode(),"---接口超时，降级回调，线程--"+Thread.currentThread().getName());
    }


    /***
     * 服务熔断接口
     * @return
     */
    @HystrixCommand(fallbackMethod = "payCircuitBreakerFallback"  //回调方法
          ,commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true")   //开启断路器
           ,@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000") //时间窗口
           ,@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "3") //请求次数阈值，时间窗口内达到请求阈值则开启熔断
           ,@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50")//异常百分比阈值，时间窗口内异常率达到阈值则开启熔断
    })
    public ResultMessage payCircuitBreaker(String id ){

        System.out.println("-------熔断接口正常调用-----"+id);
        //int a = 1/0 ;
        return new ResultMessage(ResultCode.OK.getCode(),"熔断接口正常调用,线程"+Thread.currentThread().getName());

    }

    /***
     * 服务熔断回调方法
     * @return
     */
    public ResultMessage payCircuitBreakerFallback(String id ){

        System.out.println("-------开启熔断-----"+id);
        return new ResultMessage(ResultCode.OK.getCode(),"开启熔断，线程"+Thread.currentThread().getName());
    }



}
